<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';


import { useVbenForm } from '#/adapter/form';
import { getCompanyList } from '#/api/spuBom';
import {exportContract} from "#/api/supply";
import {message} from "ant-design-vue";


const emit = defineEmits(['refresh']);
const categorysList = ref([]);
const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'Select',
      fieldName: 'company_name',
      label: '合同抬头',
      rules: 'required',
      componentProps: {
        allowClear: true,
        filterOption: (input, option) => {
          return (option?.label || '')
            .toLowerCase()
            .includes(input.toLowerCase());
        },
        options: categorysList,
        showSearch: true,
      },
    },
  ],
  showDefaultActions: false,
});
const rowData = ref();
const contractType = ref();

const [Modal, modalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    modalApi.close();
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) return;
    const { data, contract_type } = modalApi.getData<Record<string, any>>();
    rowData.value = data
    contractType.value = contract_type;

    const parmas = {
      limit: 30,
      is_remote: true,
      page: 1,
      select: true,
    };
    getCompanyList(parmas).then((res) => {
      categorysList.value = res.map((item: any) => ({
        label: item.name,
        value: item.id,
      }));
    });
  },
  title: '导出前资料填写',
});

function onSubmit(values: Record<string, any>) {
  modalApi.lock(true);
  const data = values;

  const parmas = {
    company_name: data.company_name,
    contract_type: contractType.value,
    ids: rowData.value,
  };
  exportContract(parmas).then((res: any) => {
    modalApi.unlock();
    if (res.data.code === 1) {
      message.success(res.data.msg);
      window.open(res.data.data.file_url);
      emit('refresh');
      modalApi.close();
    } else {
      modalApi.unlock();
      message.error(res.data.msg);
    }
  });
}
</script>
<template>
  <Modal>
    <Form />
  </Modal>
</template>
